<?php 
// +----------------------------------------------------------------------
// | CRMUU-企微SCRM是专业的企业微信第三方源码系统.
// +----------------------------------------------------------------------
// | [CRMUU] Copyright (c) 2022 http://crmuu.com All rights reserved.
// +----------------------------------------------------------------------

namespace app\wework\model\user\autogroup;
use think\facade\Db;
use think\facade\Session;
use think\facade\Log;
use app\wework\model\QyWechatApi;
require "../extend/Phpqrcode/phpqrcode.php";

/**
* 自动拉群
**/
class AutoPullGroupModel {

	/*
	* 自动拉群列表
	*/
	static public function list($page,$size,$url,$name=NULL,$grouping_id=NULL){
		$wid = Session::get("wid");
		$where["wid"] = $wid;
		$where["delete"] = 0;
		$code = new \QRcode();
		if($grouping_id)$where["grouping_id"] = $grouping_id;
		$res = Db::table("kt_wework_group_auto")
				->where($where);
		if($name)$res = $res->whereLike('name','%'.$name.'%');
		$group_list['count'] = $res->count();
		$group_list['item'] = $res->page($page,$size)
				->json(["welcome_text","tags","standby","astrict","staffs"])
				->filter(function($data) use($url,$code){
					$data["tags"] = array_column(Db::table("kt_wework_tag")->where(["tag_id"=>$data["tags"]])->field("tag_name")->select()->toArray(), "tag_name");
					$data["staffs"] = array_column(Db::table("kt_wework_staff")->where(["id"=>$data["staffs"]])->field("name")->select()->toArray(), "name");
					$data["standby"] = array_column(Db::table("kt_wework_staff")->where(["id"=>$data["standby"]])->field("name")->select()->toArray(), "name");
					$data["group_data"] = Db::table("kt_wework_group_auto_data")
										->where(["pid"=>$data["id"]])
										->field("code,group_id,size,status")
										->filter(function($group) use($data){
											if($data["type"] == 1)$group["name"] = Db::table("kt_wework_group")->where(["id"=>$group["group_id"]])->field("name")->find()["name"];
											return $group;
										})
										->select()
										->toArray();
					$data["qrcodes"] = self::qrcode($code,$data["name"],$data["id"],$url);
					return $data;
				})
				->select()
				->toArray();
		$group_list['page'] = $page;
		$group_list['size'] = $size;
		return $group_list;
	}

	//分組列表
	static public function groupingList(){
		$wid = Session::get("wid");
		$where["wid"] = $wid;
		$res = Db::table("kt_wework_group_auto_grouping")
					->where($where)
					->field("name,id")
					->filter(function($data){
						$data["size"] = Db::table("kt_wework_group_auto")->where(["grouping_id"=>$data["id"],"delete"=>0])->count();
						return $data;
					})
					->select()
					->toArray();
		return $res;
	}

	//生成二维码
	static public function qrcode($code=NULL,$name,$id,$url){
	    if(!$code)$code = new \QRcode();
		$path = '../public/static/wework/qrcode/';
		if(!file_exists($path))mkdir($path,0777,true);
	    $res = $code->png($url."/wework/h5.AutoPullGroup/index.html?id=".$id,$path.$name.".png", 6);
	    if(!$res)$res = $url."/static/wework/qrcode/".$name.".png";

	    return $res;
	}

	/**
	* 添加自动拉群
	*/
	static public function add($type,$join_type,$name,$grouping_id,$staffs,$is_astrict,$astrict=NULL,$standby=NULL,$is_tag,$tags,$welcome_text,$skip_verify,$group_name,$group_welcome,$group_image,$is_group_name,$is_group_welcome,$id=NULL){
		$wid = Session::get("wid");
		$data["wid"] = $wid;
		$data["join_type"] = $join_type;
		$data["type"] = $type;
		$data["name"] = $name;
		$data["grouping_id"] = $grouping_id;
		$data["is_tag"] = $is_tag;
		$data["is_astrict"] = $is_astrict;
		$data["skip_verify"] = $skip_verify;
		$data["group_image"] = $group_image;
		$data["group_name"] = $group_name;
		$data["is_group_welcome"] = $is_group_welcome;
		$data["is_group_name"] = $is_group_name;
		$data["group_welcome"] = $group_welcome;
		$data["create_time"] = date("Y-m-d H:i:s",time());
		$data["staffs"] = json_encode($staffs,320);
		$data["tags"] = json_encode($tags,320);
		$data["standby"] = json_encode($standby,320);
		$data["welcome_text"] = json_encode($welcome_text,320);
		if(!$id){
			$id = Db::table("kt_wework_group_auto")->insertGetId($data);
			Db::table("kt_wework_group_auto")->where(["id"=>$id])->save(["state"=>"auto".$id]);
		}else{
			$res = Db::table("kt_wework_group_auto")->where(["id"=>$id])->update($data);
		}
		if($is_astrict == 1 && count($astrict)){
			foreach ($astrict as $value){
				$astrict_data["wid"] = $wid;
				$astrict_data["pid"] = $id;
				$astrict_data["staff_id"] = $value["id"];
				$astrict_data["size"] = $value["size"];
				$astrict_id = Db::table("kt_wework_group_auto_astrict")->where(["wid"=>$wid,"pid"=>$id,"staff_id"=>$value["id"]])->find();
				if($astrict_id)Db::table("kt_wework_group_auto_astrict")->where(["wid"=>$wid,"pid"=>$id,"staff_id"=>$value["id"]])->save($astrict_data);
				if(!$astrict_id)Db::table("kt_wework_group_auto_astrict")->insertGetId($astrict_data);
			}
		}

		return $id;
	}

	/*
	* 自动拉群群聊信息
	*/
	static public function addData($data,$id){
		$wid = Session::get("wid");
		foreach ($data as $key=>$group) {
			$orders = $key+1;
			$datas[$orders] = [
				'orders'=>$orders,
				'wid'=>$wid,
				'pid'=>$id,
				'group_id'=>$group["group_id"],
				'code'=>$group["code"],
				'size'=>$group["size"],
				'status'=>2,
			];
			$group_data[] = $group["group_id"];
			if($orders === 1)$datas[$orders]["status"] = 1;
		}
		$res = Db::table("kt_wework_group_auto_data")->insertAll($datas);

		return $group_data;
	}

	/*
	* 自动拉群群聊信息
	*/
	static public function addDatas($data,$id){
		$wid = Session::get("wid");
		foreach ($data as $key=>$group) {
			$datas[$key] = [
				'orders'=>$key+1,
				'wid'=>$wid,
				'pid'=>$id,
				'code'=>$group["code"],
				'size'=>$group["size"],
				'status'=>2,
			];
			$datas[0]["status"] = 1;
		}
		$res = Db::table("kt_wework_group_auto_data")->insertAll($datas);

		return $res;
	}

	//修改入群欢迎语
	static public function updata($group_data,$id){
		$wid = Session::get("wid");
		Db::table("kt_wework_group_auto_data")->where(["status"=>2,"pid"=>$id])->delete();
		$ids = array_column(Db::table("kt_wework_group_auto_data")->where(["pid"=>$id])->field("id")->select()->toArray(), "id");
		$orders = Db::table("kt_wework_group_auto_data")->where(["pid"=>$id])->count();
		$data = [];
		$group_datas = [];
		foreach ($group_data as $group){
			if(isset($group["id"])){
				if(in_array($group["id"],$ids))continue;
			}
			$orders = $orders+1;
		 	$data[] = [
				'orders'=>$orders,
				'wid'=>$wid,
				'pid'=>$id,
				'group_id'=>$group["group_id"],
				'code'=>$group["code"],
				'size'=>$group["size"],
				'status'=>2,
			];
			$group_datas[] = $group["group_id"];
		}
		if(count($data))$res = Db::table("kt_wework_group_auto_data")->insertAll($data);

		return $group_datas;
	}

	static public function updatas($group_data,$id){
		$wid = Session::get("wid");
		Db::table("kt_wework_group_auto_data")->where(["status"=>2,"pid"=>$id])->delete();
		$ids = array_column(Db::table("kt_wework_group_auto_data")->where(["pid"=>$id])->field("id")->select()->toArray(), "id");
		$orders = Db::table("kt_wework_group_auto_data")->where(["pid"=>$id])->count();
		$data = [];
		foreach ($group_data as $group){
			if(isset($group["id"])){
				if(in_array($group["id"],$ids))continue;
			}
			$orders = $orders+1;
		 	$data[] = [
				'orders'=>$orders,
				'wid'=>$wid,
				'pid'=>$id,
				'code'=>$group["code"],
				'size'=>$group["size"],
				'status'=>2,
			];
		}
		if(count($data))$res = Db::table("kt_wework_group_auto_data")->insertAll($data);

		return "true";
	}

	/*
	* 自动拉群群聊信息
	*/
	static public function users($staffs){
		$wid = Session::get("wid");
		$res = Db::table("kt_wework_staff")->where(["id"=>$staffs])->field("userid")->select()->toArray();

		return array_column($res, "userid");
	}

	//自动拉群，获取群聊详情+群主
	static public function groupData($groups){
		$wid = Session::get("wid");
		$res = Db::table("kt_wework_group")
					->where(["id"=>$groups])
					->field("name,staff_id")
					->filter(function($data){
						$data["user"] = Db::table("kt_wework_staff")->field("userid")->find(["id"=>$data["staff_id"]]);
						return $data;
					})
					->select()
					->toArray();
		return $res;
	}

	//自动拉群分组添加修改
	static public function addGrouping($name,$id=NULL){
		$wid = Session::get("wid");
		$data["wid"] = $wid;
		$data["name"] = $name;
		$data["ctime"] = date("Y-m-d H:i:s");
		if(!$id){
			$is_set = Db::table("kt_wework_group_auto_grouping")->where(["name"=>$name])->find();
			if($is_set)return "error";
			$res = Db::table("kt_wework_group_auto_grouping")->insertGetId($data);
		}
		if($id){
			$is_set = Db::table("kt_wework_group_auto_grouping")->where(["name"=>$name])->where("id","<>",$id)->find();
			if($is_set)return "error";
			$res = Db::table("kt_wework_group_auto_grouping")->where(["id"=>$id])->save($data);
		}
		return $res;
	}

	//创建渠道码入库
	static public function upAuto($add_way,$auto_id,$type=NULL){
		if($type){
			$data["standby_config_id"] = $add_way["config_id"];
			$data["standby_qrcode"] = $add_way["qr_code"];
		}else{
			$data["config_id"] = $add_way["config_id"];
			$data["qr_code"] = $add_way["qr_code"];
		}
		$res = Db::table("kt_wework_group_auto")->where(["id"=>$auto_id])->save($data);

		return $res;
	}


	//创建渠道码入库
	static public function del($id){
		$res = Db::table("kt_wework_group_auto")->where(["id"=>$id])->update(["delete"=>1]);
		Db::table("kt_wework_group_auto_data")->where(["pid"=>$id])->update(["delete"=>1]);
		
		return $res;
	}
	//创建入群欢迎语id入库
	static public function upWelcome($template_id,$auto_id){
		$data["template_id"] = $template_id;
		$res = Db::table("kt_wework_group_auto")->where(["id"=>$auto_id])->save($data);

		return $res;
	}

	//批量分组
	static public function groupings($ids,$grouping_id){
		$res = Db::table("kt_wework_group_auto")->where(["id"=>$ids])->update(["grouping_id"=>$grouping_id]);

		return $res;
	}

	//编辑拉群数据
	static public function getInfo($id,$field=NULL){
		$wid = Session::get("wid");
		$res = self::info($id,$field);
		$res["staffs"] = Db::table("kt_wework_staff")
								->where(["id"=>$res["staffs"]])->field("name,avatar,id")
								->filter(function($data) use($wid,$res){
									$astrict = Db::table("kt_wework_group_auto_astrict")->where(["wid"=>$wid,"pid"=>$res["id"],"staff_id"=>$data["id"]])->find();
									$data["status"] = 0;
									if($astrict) $data["status"] = 1;
									if($astrict) $data["size"] = $astrict["size"];
									return $data;
								})
								->select()->toArray();
		$res['tags'] = Db::table('kt_wework_tag')->field('tag_name')->where(['tag_id'=>$res['tags']])->field("tag_name,tag_id")->select()->toArray();
		$res["standby"] = Db::table("kt_wework_staff")->where(["id"=>$res["standby"]])->field("name,avatar,id")->select()->toArray();
		$res["group_data"] = Db::table("kt_wework_group_auto_data")
										->where(["pid"=>$id])
										->field("code,group_id,size,status,id")
										->filter(function($data) use($wid,$res){
											if($data["group_id"])$data["name"] = Db::table("kt_wework_group")->where(["id"=>$data["group_id"]])->field("name")->find()["name"];
											return $data;
										})
										->select()->toArray();

		return $res;
	}

	//获取本条入群欢迎语数据
	static public function info($id,$field=NULL){
		if($field)$res = Db::table("kt_wework_group_auto")->field($field)->json(["welcome_text","standby","staffs","tags","upper"])->where(["id"=>$id])->find();
		if(!$field)$res = Db::table("kt_wework_group_auto")->json(["staffs","tags","standby","welcome_text"])->where(["id"=>$id])->find();

		return $res;
	}

	//获取已选中的数据详情
	static public function infos($ids){
		$res = Db::table("kt_wework_group_auto")->where(["id"=>$ids])->field("id,name")->select()->toArray();

		return $res;
	}


	//获取已选中的数据详情
	static public function delGrouping($id){
		$res = Db::table("kt_wework_group_auto_grouping")->where(["id"=>$id])->delete();

		return $res;
	}

	//批量修改
	static public function batchUpd($ids,$user_set,$staffs,$standby,$is_tag,$tags,$skip_verify,$is_astrict,$astrict,$is_group,$group_text){
		$wid = Session::get("wid");
		$res = Db::table("kt_wework_group_auto")->where(["id"=>$ids])->select()->toArray();
		if($user_set == 1 || $is_group == 1){
			$params['user'] = self::users($staffs);
			$params['skip_verify'] = $skip_verify?true:false;
			foreach($res as $value){
				$data = [];
				//跳过直接入群的配置
				if($value["join_type"] == 2){
					$params['user'] = self::users($staffs);
					$params['config_id'] = $value["config_id"];
					$upd = QyWechatApi::updateContactWay($params);
					if($upd["errcode"] != 0)return error("操作失败",$upd["errcode"]);
					$data["skip_verify"] = $skip_verify;
					if($is_astrict == 1 && count($astrict)){
						foreach ($astrict as $astrict_value){
							$astrict_data["wid"] = $wid;
							$astrict_data["pid"] = $value["id"];
							$astrict_data["staff_id"] = $astrict_value["id"];
							$astrict_data["size"] = $astrict_value["size"];
							$astrict_id = Db::table("kt_wework_group_auto_astrict")->where(["wid"=>$wid,"pid"=>$value["id"],"staff_id"=>$astrict_value["id"]])->find();
							if($astrict_id)Db::table("kt_wework_group_auto_astrict")->where(["wid"=>$wid,"pid"=>$value["id"],"staff_id"=>$astrict_value["id"]])->save($astrict_data);
							if(!$astrict_id)Db::table("kt_wework_group_auto_astrict")->insertGetId($astrict_data);
						}
					}
					$data["tags"] = json_encode($tags,320);
					$data["staffs"] = json_encode($staffs,320);
					$data["standby"] = json_encode($standby,320);
					$data["is_astrict"] = $is_astrict;
					$data["is_tag"] = $is_tag;
					if(count($standby)){
						if($value["standby_config_id"]){
							$param['user'] = self::users($standby);
							$param['config_id'] = $value["standby_config_id"];
							$standby_upd = QyWechatApi::updateContactWay($param);
							if($upd["errcode"] != 0)return error("操作失败",$upd["errcode"]);
						}else{
							$param['type'] = 2;
							$param['scene'] = 2;
							$param['user'] = self::users($standby);
							$param['state'] = $value["state"];
							$param['skip_verify'] = $skip_verify?true:false;
							$add_way = QyWechatApi::addContactWay($param);
							if($add_way["errcode"] != 0)return error("操作失败",$add_way["errcode"]);
							$data["standby_config_id"] = $add_way["config_id"];
							$data["standby_qrcode"] = $add_way["qr_code"];
						}
					}
				}
				if($is_group)$data["welcome_text"] = json_encode($group_text,320);
				Db::table("kt_wework_group_auto")->where(["id"=>$value["id"]])->update($data);
			}
		}
		return success("操作成功");
	}

	static public function getGroups(){
		$wid = Session::get("wid");
		$res = array_column(Db::table("kt_wework_group_auto_data")->where(["wid"=>$wid,"delete"=>0])->field("group_id")->select()->toArray(), "group_id");

		return $res;
	}

	//查询上下限成员
	//below 为上线的
	//upper 为下线的
	static public function below($res){
		$wid = Session::get("Wid");
		$staffs = array_column($res["staffs"], "id");
		$upper = [];
		if($res["upper"])$staffs = array_diff($res["staffs"],$res["upper"]);
		$below = Db::table("kt_wework_staff")->where(["id"=>$staffs])->field("id,name,avatar")->select()->toArray();
		if($res["upper"])$upper = Db::table("kt_wework_staff")->where(["id"=>$res["upper"]])->field("ia,name,avatar")->select()->toArray();

		return ["below"=>$below,"upper"=>$upper];
	}

}